const router = require('koa-router')()
const CreateSequelize = require('./sequelize')
let sequelize = new CreateSequelize()
sequelize.init_sequeleze()

router.get('/getUser', async (ctx, next) => {
    let res = await sequelize.select('select * from user')
    ctx.body = res
})
router.get('/register', async (ctx, next) => {
    console.log(ctx.query);
    let { user, pass } = ctx.query
    await sequelize.select(`insert into user(img,name,user,pass,email,date,code,miao,dates,flag,jifen,biaoqian,gender,dengji,flages) values('https://img1.baidu.com/it/u=2115534099,3269649209&fm=26&fmt=auto','新用户','${user}','${pass}','','','','','','','0','-','[10,20,30]','V1','false')`)

    ctx.body = '连接成功'
})
router.get('/getCircle', async (ctx, next) => {
    let res = await sequelize.select('select * from circle')
    ctx.body = res
})
// 获取总数据
router.get('/getData', async (ctx, next) => {
    let str = await sequelize.select("select * from data")
    let res = str.filter(item => {
        return item.state === '1'
    })
    ctx.body = res
})
// 获取总数据
router.get('/getStartData', async (ctx, next) => {
    // console.log(ctx.query.limitnum)
    let str = await sequelize.select(`select * from data limit ${ctx.query.limitnum * 6},6`)
    let res = str.filter(item => {
        return item.state === '1'
    })
    // console.log(res);
    ctx.body = res
})



// -------------------------------------


// 购物车接口
// 获取购物车数据
router.get("/getShopCar", async (ctx, next) => {
    let res = await sequelize.select("select * from shopcar")
    ctx.body = res
})
// 购物车数量的加加减减
router.get("/addNum", async (ctx, next) => {
    let { res } = ctx.query
    let result = await sequelize.select("select * from shopcar")
    let index = result.findIndex(item => {
        return item.id === res
    })
    let data = await sequelize.select(`update shopcar set num="${result[index].num + 1}" where id="${res}"`).catch(err => {
        console.log(err);
    })

    // 重新获取数据返回给页面
    let newData = await sequelize.select("select * from shopcar")
    ctx.body = newData
})
router.get("/minusShopCarNum", async (ctx, next) => {
    let { res } = ctx.query
    let result = await sequelize.select("select * from shopcar")

    let index = result.findIndex(item => {
        return item.id === res
    })
    if (result[index].num <= 1) {
        console.log('至少购买一个' + result[index].num + '个');
    } else {
        let data = await sequelize.select(`update shopcar set num="${result[index].num - 1}" where id="${res}"`).catch(err => {
            console.log(err);
        })

        // 重新获取数据返回给页面
        let newData = await sequelize.select("select * from shopcar")
        ctx.body = newData
    }
})
// 修改isCheck值
router.get("/setIsCheck", async (ctx, next) => {
    let { res } = ctx.query
    console.log(res);
    let result = await sequelize.select("select * from shopcar")

    let index = result.findIndex(item => {
        return item.id === res
    })
    let data = await sequelize.select(`update shopcar set isCheck="${!JSON.parse(result[index].isCheck)}" where id="${result[index].id}"`).catch(err => {
        console.log(err);
    })

    // // 重新获取数据返回给页面
    let newData = await sequelize.select("select * from shopcar")
    ctx.body = newData
})
// 全选 
router.get("/isCheckAll", async (ctx, next) => {
    let { res } = ctx.query
    // let data = await sequelize.select("select * from cardata")
    // data.forEach(async item => {

    // })
    await sequelize.select(`update shopcar set isCheck="${res}"`).catch(err => {
        console.log(err);
    })
    // 重新获取数据返回给页面
    let newData = await sequelize.select("select * from shopcar")
    ctx.body = newData
})
// 提交订单
router.get("/submitoOrder", async (ctx, next) => {
    let { data } = ctx.query
    let dataAll = JSON.parse(data)
    dataAll.forEach(async item => {
        await sequelize.select(`insert into orderdata(img,isCheck,name,num,price,state,flag,page,Js,Xq,Pj,oldId,time,countPrice,yhq,yunf) values('${item.img}','${item.isCheck}','${item.name}','${item.num}','${item.price}','${item.state}','${item.flag}','${item.page}','${item.Js}','${item.Xq}','${item.Pj}','${item.id}','${item.time}','${item.countPrice}','${item.yhq}','${item.yunf}')`).catch(err => {
            console.log(err);
        })
        await sequelize.select(`delete from shopcar where id="${item.id}"`).catch(err => {
            console.log(err);
        })
    })

    // let res = await sequelize.select("select * from orderData")
    // ctx.body = res
    ctx.body = '添加成功'
})
// 立即支付
router.get("/nowPay", async (ctx, next) => {
    let { data } = ctx.query
    console.log(data);
    JSON.parse(data).forEach(async item => {
        await sequelize.select(`update orderdata set state='${item.state}' where oldId='${item.id}'`)
    })
    ctx.body = "支付完成"
})


// 加入购物车
router.get("/addCarData", async (ctx, next) => {
    let { res } = ctx.query
    let obj = JSON.parse(res)
    let getCarData = await sequelize.select('select * from shopcar')
    let i = getCarData.findIndex(item => {
        return item.id == obj.id
    })
    if (i !== -1) {
        await sequelize.select(`update shopcar set num="${getCarData[i].num + obj.num}" where id='${JSON.parse(getCarData[i].id)}'`).catch(err => {
            console.log(err);
        })
    } else {
        await sequelize.select(`insert into shopcar (id,img,name,page,price,Js,Pj,Xq,isCheck,num) values('${obj.id}','${obj.img}','${obj.name}','${JSON.stringify(obj.page)}','${obj.price}','${obj.Js}','${JSON.stringify(obj.Pj)}','${JSON.stringify(obj.Xq)}','${obj.isCheck}','${obj.num}')`).catch(err => {
            console.log(err);
        })
    }
    let result = await sequelize.select(`select * from shopcar`).catch(err => {
        console.log(err);
    })
    ctx.body = result
})

// 删除购物车
router.get("/delData", async (ctx, next) => {
    let { data } = ctx.query
    let newData = JSON.parse(data)
    newData.forEach(async item => {
        await sequelize.select(`delete from shopcar where id="${item.id}"`)
    })
    let res = await sequelize.select(`select * from shopcar`)
    ctx.body = res
})

//------------------------------------------
router.get('/searchgoods', async (ctx, next) => {
    console.log(ctx.query);
    if (ctx.query.onum === "0") {
        var res = await sequelize.select(`select * from searchdata where name like '%${ctx.query.name}%' or Tag='${ctx.query.name}' `)
    }
    if (ctx.query.onum === "1" && ctx.query.otype === "price") {
        var res = await sequelize.select(`select * from searchdata where name like '%${ctx.query.name}%' or Tag='${ctx.query.name}' order by searchdata.price`)
    } else if (ctx.query.onum === "2" && ctx.query.otype === "price") {
        var res = await sequelize.select(`select * from searchdata where name like '%${ctx.query.name}%' or Tag='${ctx.query.name}' order by searchdata.price desc`)
    } else if (ctx.query.onum === "1" && ctx.query.otype === "paynum") {
        var res = await sequelize.select(`select * from searchdata where name like '%${ctx.query.name}%' or Tag='${ctx.query.name}' order by searchdata.paynum`)
    } else if (ctx.query.onum === "2" && ctx.query.otype === "paynum") {
        var res = await sequelize.select(`select * from searchdata where name like '%${ctx.query.name}%' or Tag='${ctx.query.name}' order by searchdata.paynum desc`)
    }
    // console.log(ctx.query.name);
    if (res.length === 0) {
        ctx.body = { code: "02", msg: "没有该关键字" }
    } else {
        ctx.body = { data: res, onum: ctx.query.onum, otype: ctx.query.otype }
    }
})

router.get('/showAllTags', async (ctx, next) => {
    let str = await sequelize.select("select Tag from data");
    let res = str.filter(item => {
        return item.state === '1'
    })
    let sendarr = [];
    res.forEach(item => {
        if (sendarr.indexOf(item.Tag) === -1) {
            sendarr.push(item.Tag)
        }
    })
    // console.log(sendarr);
    ctx.body = sendarr
})

module.exports = router
//添加地址信息
router.get('/isChec', async (ctx, next) => {
    let { value, house, userName, cellPhone, addressLoder } = ctx.query
    await sequelize.select(`INSERT INTO list(val, house, userName, cellPhone, addressLoder)
    VALUES('${value}','${house}','${userName}','${cellPhone}','${addressLoder}')`).catch((err) => { })
    let str = await sequelize.select('select * from list')
    ctx.body = str
})
//获取地址
router.get('/addCar', async (ctx, next) => {
    let str = await sequelize.select('select * from list')
    ctx.body = str
})
//查找地址
router.get('/filter', async (ctx, next) => {
    let { val } = ctx.query
    let str = await sequelize.select('select * from list')
    let car = str.filter((item) => {
        return item.val.indexOf(val) > -1
    })
    ctx.body = car
})
//获取列表数据
router.get('/dataList', async (ctx, next) => {
    let str = await sequelize.select('select * from data')
    let res = str.filter(item => {
        return item.state === '1'
    })
    ctx.body = res
})
router.get('/getCircle', async (ctx, next) => {
    let res = await sequelize.select('select * from circle')
    ctx.body = res
})
router.get('/addShop', async (ctx, next) => {
    let { id, img, name, page, price, Js, Pj, Xq, isCheck, num } = ctx.query
    let res = await sequelize.select('select * from shopcar')
    let index = res.findIndex(item => {
        return id === item.id
    })
    if (index !== -1) {
        await sequelize.select(`update shopcar set num=${res[index].num + Number(num)} where id='${res[index].id}'`)
    } else {
        await sequelize.select(`insert into shopcar(id,img,name,page,price,Js,Pj,Xq,isCheck,num) values('${id}','${img}','${name}','${page}','${price}','${Js}','${Pj}','${Xq}','${isCheck}','${num}')`)
    }
    ctx.body = '连接成功'
})


module.exports = router
